"""
系统日志模型
"""
from datetime import datetime
from app.extensions import db


class SystemLog(db.Model):
    """系统日志表"""
    __tablename__ = 'system_logs'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
    action = db.Column(db.String(50))
    resource_type = db.Column(db.String(50))
    resource_id = db.Column(db.String(50))
    ip_address = db.Column(db.String(45))
    status = db.Column(db.Enum('success', 'failed'), default='success')
    level = db.Column(db.Enum('INFO', 'WARNING', 'ERROR'), default='INFO', index=True)
    message = db.Column(db.Text)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    
    # 关系
    user = db.relationship('User', backref='system_logs')
    
    __table_args__ = (
        db.Index('idx_timestamp_desc', 'timestamp', postgresql_using='btree'),
        db.Index('idx_user_timestamp', 'user_id', 'timestamp'),
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'action': self.action,
            'resource_type': self.resource_type,
            'resource_id': self.resource_id,
            'ip_address': self.ip_address,
            'status': self.status,
            'level': self.level,
            'message': self.message,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None,
        }










